package com.itheima.homework.dao.impl;

import com.itheima.homework.dao.StudentDao;
import com.itheima.homework.pojo.Student;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Component
public class StudentDaoImpl implements StudentDao {
    @Override
    public Student selectOneByUsername(String username) {
        return STUDENTS.stream().filter(student -> Objects.equals(student.getUsername(), username)).findAny().orElse(null);
    }

    @Override
    public void insertOne(Student student) {
        STUDENTS.add(student);
    }

    @Override
    public void updateByUsername(Student student) {
        STUDENTS.stream().filter(item -> Objects.equals(item.getUsername(), student.getUsername())).findAny().ifPresent(item -> {
            if (Objects.nonNull(student.getPassword())) {
                item.setPassword(student.getPassword());
            }
            if (Objects.nonNull(student.getAge())) {
                item.setAge(student.getAge());
            }
            if (Objects.nonNull(student.getGender())) {
                item.setGender(student.getGender());
            }
        });
    }

    @Override
    public List<Student> selectList() {
        return STUDENTS.stream().peek(Student::desensitization).collect(Collectors.toList());
    }

    @Override
    public void deleteBatch(List<String> usernameList) {
        STUDENTS.removeIf(student -> usernameList.contains(student.getUsername()));
    }
}
